package com.ruoyi.drone.interceptor;

import com.ruoyi.drone.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的Authorization
        String authHeader = request.getHeader("Authorization");
        
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"未提供有效的认证信息\"}");
            return false;
        }

        // 提取token
        String token = jwtUtils.getTokenFromHeader(authHeader);
        
        System.out.println("JWT拦截器 - 原始token: " + token);
        
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"Token格式错误\"}");
            return false;
        }

        // 验证token
        try {
            boolean isExpired = jwtUtils.isTokenExpired(token);
            System.out.println("JWT拦截器 - token是否过期: " + isExpired);
            
            if (isExpired) {
                System.out.println("JWT拦截器 - token已过期，当前时间: " + new java.util.Date());
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"msg\":\"Token已过期\"}");
                return false;
            }

            // 将用户信息存储到request中，供后续使用
            Long userId = jwtUtils.getUserIdFromToken(token);
            String phone = jwtUtils.getPhoneFromToken(token);
            
            System.out.println("JWT拦截器 - userId: " + userId + ", phone: " + phone);
            
            request.setAttribute("userId", userId);
            request.setAttribute("phone", phone);
            
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"Token验证失败\"}");
            return false;
        }
    }
}
